#!/usr/bin/env python3 
# -*- coding: utf-8 -*-
#-------------------------------------------------------
#	FileName	: spec.py
#	Author		：hpy
#	Date		：2024年03月02日
#	Description	：
#-------------------------------------------------------
from sys import argv
import numpy as np
import math 
#-------------------------------------------------------
#	从txt文件加载光谱数据
#   文件格式：第一列x  第二列y
#-------------------------------------------------------
def loadreadtxt(file_name):
    data = []
    file = open(file_name,'r')  #打开文件
    file_data = file.readlines() #读取所有行
    for row in file_data:
        tmp_list = row.split(' ') #按‘，’切分每行的数据
        tmp_list[-1] = tmp_list[-1].replace('\n','') #去掉换行符 \n
        # print(tmp_list)
        data.append(tmp_list) #将每行数据插入data中

    return data 


# 矩阵遍历打印到终端
def mat_traverse(mat):
    rows, cols = mat.shape              # 获取矩阵的行数和列数
    for i in range(rows):               # 按照行来遍历
        for j in range(cols):           # 对第i行进行遍历
            print(mat[i, j], end=' ')   # 输出第i行第j列元素（读）
        print("")


def mat_snr(mat,cm_start,cm_end):
    rows, cols = mat.shape              # 获取矩阵的行数和列数
    idx_start = -1
    idx_end = 0
    for i in range(rows):               # 按照行来遍历
        if(mat[i,0]>=cm_start and mat[i,0]<= cm_end):
            idx_end = i+1 
            if idx_start == -1 :
                idx_start = i
 

    # 截取 波数在   cm_start ~ cm_end 的数据
    data = mat[idx_start:idx_end , :]
    if data.shape[0] < 2:
        return "NaN"
    
    # 矩阵按行求最大值和最小值
    data_max= np.max(data[: , 1:],axis=0)
    data_min= np.min(data[: , 1:],axis=0)


    data_dlt = data_max - data_min
    data_snr = 100.0 / data_dlt
    # 求每行的平均信噪比
    snr_ave = np.average(data_snr[: , :],axis=1)
    data_snr = np.c_[data_snr,snr_ave]
    return data_snr
    # print(data_max)
    # print(data_min)
    # print(100.0/data_dlt)
            
cm = np.mat([
    [901,1000],
    [2000,2100],
    [4000,4100]
])

if __name__=="__main__":
    # 加载背景光谱
    back = np.mat( loadreadtxt('src/background.back') ,  dtype=np.float64 )
    spec = back[: , 0:1]
    
    # 获取光谱
    first = True 
    for arg in argv:
        if first:
            first = False
            continue

        
        # print (arg)
        # 加载能量数据
        data = np.mat( loadreadtxt(arg) ,  dtype=np.float64 )
        # 计算透射率
        data[: , 1:2] = data[: , 1:2] / back[: , 1:2] * 100
        spec = np.c_[spec,data[: , 1:2]]

    # 矩阵按行求方差
    # spec[: , 1:] = np.std(spec[: , 1:],axis=1)

    # 按行求平均值
    # ave = np.average(spec[: , 1:], axis=1) 
    # spec = np.c_[spec,ave]
    # print(ave)

    # mat_snr(spec,4000.0,4100.0)

    for r in range(cm.shape[0]):
        # 设置打印选项，关闭换行
        np.set_printoptions(threshold=np.inf, linewidth=np.inf)
        print(cm[r,0],'~' ,cm[r,1],mat_snr(spec,cm[r,0],cm[r,1]))


    # mat_traverse(spec[:,0:1]>=2000 and spec[:,0:1]<=2100)

    # back = np.mat( loadreadtxt('src/background.back') ,  dtype=np.float64 )
    # data = np.mat( loadreadtxt(srcfile) ,  dtype=np.float64 )
    # ans  = np.copy(back)

    # 计算透过率
    # ans[: , 1:2] =data[: , 1:2] / back[: , 1:2] * 100 

    # 计算吸光度
    # ans[: , 1:2] = np.log(back[: , 1:2] / data[: , 1:2] ) / np.log(10)

    # 设置打印所有的矩阵数据
    # np.set_printoptions(threshold=np.inf)
    # print(spec)